
import java.io.BufferedReader;  
import java.io.BufferedWriter;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileWriter;  
import java.io.InputStream;  
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;  
  
/* 
 * 替换文件（如果该文件含有子目录，则包括子目录所有文件）中某个字符串并写入新内容（Java代码实现）. 
 *  
 *原理：逐行读取源文件的内容，一边读取一边同时写一个*.tmp的文件。 
 *当读取的行中发现有需要被替换和改写的目标内容‘行’时候，用新的内容‘行’替换之。  
 *最终，删掉源文件，把*.tmp的文件重命名为源文件名字。 
 * 
 *注意！代码功能是逐行读取一个字符串，然后检测该字符串‘行’中是否含有替换的内容，有则用新的字符串‘行’替换源文件中该处整个字符串‘行’。没有则继续读。 
 *注意！替换是基于‘行’，逐行逐行的替换！ 
 * 
 * */  
public class Modify {  
  
    private String path;  
    public static  String target="throw Dept";  
    public static String newContent="throw new CoreException";  //throw new CoreException
  
    public static String[] array={"Cusv","Othr","Vals","Conf","Sys","Iobu",
    		"Aplt","Csvr","Cash","ceti","Cust","Tell","Comm","Warn","Mess",
    		"Inst","chrg","Mean","Baox","Brch","Excr","Coap","Fiac","Genl",
    		"Loan","Disc","Bkat","Colt","Doat","Obsb","Lncl","Inbb","Ivst",
    		"Ltoc","Card","Dept","Fina","Nadt","Fnex","Guoz","Simp","Inbu",
    		"Trac","Exch","Intr","Bkdf","Prnt","Clct","Yizh","Sett","Tcpj",
    		"CfError.Cusv","CfError.Othr","CfError.Vals","CfError.Conf","ApError.Sys",
    		"ApError.Iobu","ApError.Aplt","CmError.Csvr","CmError.Cash","CmError.ceti","CmError.Cust",
    		"CmError.Tell","CmError.Comm","CmError.Warn","CmError.Mess","CmError.Inst","CmError.chrg",
    		"CmError.Mean","CmError.Baox","CmError.Brch","CmError.Excr","CmError.Coap","AcError.Fiac",
    		"AcError.Genl","AtError.Loan","AtError.Disc","AtError.Bkat","AtError.Colt","AtError.Doat",
    		"AtError.Obsb","AtError.Lncl","AtError.Inbb","AtError.Ivst","AtError.Ltoc","CdError.Card",
    		"LtError.Dept","LtError.Fina","LtError.Nadt","LtError.Fnex","LtError.Guoz","LtError.Simp",
    		"LtError.Inbu","TaError.Trac","StError.Exch","StError.Intr","StError.Bkdf","StError.Prnt",
    		"StError.Clct","StError.Yizh","StError.Sett","StError.Tcpj"		
    };
    List list=Arrays.asList(array);
    public Modify(String path, String target, String newContent) {  
        // 操作目录。从该目录开始。该文件目录下及其所有子目录的文件都将被替换。  
        this.path = path;  
        // target:需要被替换、改写的内容。  
        this.target = target;  
        // newContent:需要新写入的内容。  
        this.newContent = newContent;  
  
        operation();  
    }  
  
    private void operation() {  
        File file = new File(path);  
        opeationDirectory(file);  
    }  
  
    public void opeationDirectory(File dir) {  
  
        File[] files = dir.listFiles();  
        for (int i = 0; i < files.length; i++) {  
            File f = files[i];  
            if (f.isDirectory())  
                // 如果是目录，则递归。  
                opeationDirectory(f);  
            if (f.isFile())  
                operationFile(f);  
        }  
    }  
  
    public static void operationFile(File file) {  
  
        try {  
            InputStream is = new FileInputStream(file);  
            BufferedReader reader = new BufferedReader(  
                    new InputStreamReader(is));  
  
            String filename = file.getName();  
            // tmpfile为缓存文件，代码运行完毕后此文件将重命名为源文件名字。  
            File tmpfile = new File(file.getAbsolutePath()+".tmp");  
  
            BufferedWriter writer = new BufferedWriter(new FileWriter(tmpfile));  
  
            boolean flag = false;  
            String str = null;  
            while (true) {  
                str = reader.readLine();  
  
                if (str == null)  
                    break;  
                
                if (str.contains(target)) { 
                	

                     Pattern pat = Pattern.compile("(?<=throw ).*?(?=\\()");
                     Matcher mat = pat.matcher(str);
                     while (mat.find()) {
                    	String str2=mat.group();
                    	String[] str1= str2.split("\\.");
                    	if(str1.length==2){
                    		String code=str1[0].toUpperCase()+str1[1];
                    		System.out.println(code);
                    		str=str.replace(mat.group(), "new CoreException");
                    		System.out.println(str.replace(mat.group(), "new CoreException"));
                    		Pattern pat1 = Pattern.compile("(?<=\\().*(?=\\))");
                            Matcher mat1 = pat1.matcher(str);
                            while (mat1.find()) {
                            	System.out.println();
                            	if(mat1.group().isEmpty()){
                            		str=str.replaceFirst("\\(", "(\""+code+"\",null");
                            	}else{
                            		str=str.replaceFirst("\\(", "(\""+code+"\",");
                            	}
                            }
                            System.out.println(str);
                    	}
                    	if(str1.length>2){
                    		System.out.println("3个得参数"+str1);
                    		String code=str1[1].toUpperCase()+str1[2];
                    		System.out.println(code);
                    		str=str.replace(mat.group(), "new CoreException");
                    		System.out.println(str.replace(mat.group(), "new CoreException"));
                    		Pattern pat1 = Pattern.compile("(?<=\\().*(?=\\))");
                            Matcher mat1 = pat1.matcher(str);
                            while (mat1.find()) {
                            	System.out.println();
                            	if(mat1.group().isEmpty()){
                            		str=str.replaceFirst("\\(", "(\""+code+"\",null");
                            	}else{
                            		str=str.replaceFirst("\\(", "(\""+code+"\",");
                            	}
                            }
                            System.out.println(str);
                    	}
                     }
            	 
                	
                    //writer.write(str.replaceAll(target, newContent) + "\n");  
                     writer.write(str + "\n");  
                    flag = true;  
                } else  
                    writer.write(str + "\n");  
            }  
  
            is.close();  
  
            writer.flush();  
            writer.close();  
  
            if (flag) {  
                file.delete();  
                tmpfile.renameTo(new File(file.getAbsolutePath()));  
            } else  
                tmpfile.delete();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    public static void main(String[] args) {  
//    	  File files1=new File("/home/dhlsoft/下载/app/lttsv7/apps/onl/modules/busi/ac/src/test/resources/src/main/java/cn/zte/busi");
//			Collection<File> filesCollection1 = FileUtils.listFiles(files1, new String[] { "java.tmp"}, true);
//			if (filesCollection1.size() >0 && filesCollection1 !=null) {
//				for (File file : filesCollection1) {
//					System.out.println(file.getAbsolutePath());
//					file.delete();  
//				}
//			}
//    	
//    	

//    	for (String string : array) {
//			System.out.println("throw "+string);
//			target="throw "+string;
//		    File files=new File("/home/dhlsoft/下载/app/lttsv7/apps/onl/modules/busi/ac/src/test/resources/src/main/java/cn/zte/busi");
//			Collection<File> filesCollection = FileUtils.listFiles(files, new String[] { "java"}, true);
//			if (filesCollection.size() >0 && filesCollection !=null) {
//				for (File file : filesCollection) {
//					System.out.println(file.getAbsolutePath());
//					 operationFile(file);  
//				}
//			}
//		}
	

    	 File file=   new File("/home/dhlsoft/下载/app/lttsv7/apps/onl/modules/busi/lt/src/main/java/cn/sunline/ltts/busi/lt/inbu/batchagent/IBDeduct.java");
    	
        //代码测试：假设有一个test文件夹，test文件夹下含有若干文件或者若干子目录，子目录下可能也含有若干文件或者若干子目录（意味着可以递归操作）。  
        //把test目录下以及所有子目录下（如果有）中文件含有"hi"的字符串行替换成新的"hello,world!"字符串行。  
       // new Modify(".\\test", "hi", "hello,world!");  
    	// String s = "      throw CmError.Cash.E0097(tblxjfhtmiddle.getZhanghye());;";
    	 
    	 //String s = "     		throw new CoreException(\"COMME2132\",null);";
    	 String s = "     		throw new CoreException(\"COMME2155\",lstLhpc.get(i).getGuiydaih());";
    	//;
             //throw new CoreException("COMME2155",lstLhpc.get(i).getGuiydaih());
    	 //CommTools.appendJgaoxinx(Dept.E9699_WARN(tblKdpa_zhxinx.getKehuzhao(), tblKdpa_zhxinx.getYouxriqi()));
    	 
			
    	 
    	 //throw CmError.Comm.E2066(CommTools.getTableName(kcab_wcdjtb.class),e);
//     	for (String string : array) {
// 			System.out.println("throw "+string);
// 			target="throw "+string;
//    	 
    	 if(s.contains("throw new CoreException")){
             Pattern pat = Pattern.compile("(?<=throw new CoreException\\(\").*?(?=\")");
             Matcher mat = pat.matcher(s);
             while (mat.find()) {
            	String str=mat.group();
            	String[] str1= str.split("\\.");
            	
            	
//            	".*?(?=\\()"
//            	".*?(?=\()"
//            	".*(?=\\()"
//            	".*(?=\()"
            	
               	if(str1.length>2){
            		String code=str1[1].toUpperCase()+str1[2];
            		System.out.println(code);
            		s=s.replace(mat.group(), "new CoreException");
            		System.out.println(s.replace(mat.group(), "new CoreException"));
            		Pattern pat1 = Pattern.compile("(?<=\\().*(?=\\))");
                    Matcher mat1 = pat1.matcher(s);
                    while (mat1.find()) {
                    	System.out.println();
                    	if(mat1.group().isEmpty()){
                    		s=s.replaceFirst("\\(", "(\""+code+"\",null");
                    	}else{
                    		s=s.replaceFirst("\\(", "(\""+code+"\",");
                    	}
                    	
                    }
                    System.out.println(s);
            	}
            	
            	
             }
    	 }

//     	}
    }  
    
    
    
    
    public static void main1(String[] args) {  
        //测试，传入多个参数  
        test("hello", "world", "13sd", "china", "cum", "ict");  
    }  
  
    public static void test(String... arguments) {  
        for (int i = 0; i < arguments.length; i++) {  
            System.out.println(arguments[i]);  
        }  
    }  
    
    
}  